package com.fone.player.online.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fone.player.R;
import com.fone.player.activity.BaseActivity;
import com.fone.player.client.Callback;
import com.fone.player.client.Error;
import com.fone.player.client.Request;
import com.fone.player.client.SpecllistRst;
import com.fone.player.client.SpecllistRst.Cnt;
import com.fone.player.entity.RedirectInfo;
import com.fone.player.entity.SubjectInfo;
import com.fone.player.online.adapter.LeaderboardAdapter;
import com.fone.player.online.adapter.LeaderboardGridAdapter;
import com.fone.player.util.Activity2poster;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.view.ColorBallProgressView;
import com.fone.player.widget.xlistview.XListView;
import com.fone.player.widget.xlistview.XListView.IXListViewListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class LeaderboardActivity extends BaseActivity implements OnClickListener, IXListViewListener {

	private static final String TAG = "LeaderboardActivity";
	
	private Button mLeftBt;
	private Button mRightBt;
	private TextView mTitleTv;
	
	private XListView mListView;
	
	private View headerView;
	private ImageView posterPic;
	private TextView memo;
	private TextView guide;
	
	private View footerView;
	private GridView mGridView;
	
	private LinearLayout waittingll;
	private ColorBallProgressView waittingProgress;
	
	private LeaderboardAdapter mListAdapter;
	private LeaderboardGridAdapter mGridAdapter;
	
	private DisplayImageOptions options;
	
	private String url;
	private String shost;
	private String host;
	private String clid;
	
	private String title;
	
	private List<SubjectInfo> subjectList = new ArrayList<SubjectInfo>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_leaderboard);
		getIntentData();
		iniView();
		iniData();
	}
	
	private void getIntentData(){
		Intent intent = getIntent();
		url = intent.getStringExtra("url");
		title = intent.getStringExtra("name");
	}
	
	private void iniView(){
		//TODO
		
		//title
		mLeftBt = (Button) findViewById(R.id.common_title_left_bt);
		mRightBt = (Button) findViewById(R.id.common_title_right_bt);
		mTitleTv = (TextView) findViewById(R.id.common_left_title_tv);
		mRightBt.setVisibility(View.GONE);
		mLeftBt.setOnClickListener(this);
		if(!TextUtils.isEmpty(title)){
			mTitleTv.setText(title);
		}
		
		//body
		mListView = (XListView) findViewById(R.leaderboard.list);
		mListView.setPullLoadEnable(false);
		mListView.setPullRefreshEnable(true);
		mListView.setEnableDragLoadMore(false);
		mListView.setXListViewListener(this);
		
		//header
		headerView = LayoutInflater.from(this).inflate(R.layout.view_leaderboard_header, null, false);
		posterPic = (ImageView) headerView.findViewById(R.leaderboard.pic);
		memo = (TextView) headerView.findViewById(R.leaderboard.memo);
		guide = (TextView) headerView.findViewById(R.leaderboard.guide);
		mListView.addHeaderView(headerView, null, false);
		
		//footer
		footerView = LayoutInflater.from(this).inflate(R.layout.view_leaderboard_footer, null, false);
		mGridView = (GridView) footerView.findViewById(R.leaderboard.grid);
		mGridAdapter = new LeaderboardGridAdapter(mContext, shost, subjectList);
		mGridView.setAdapter(mGridAdapter);
		mListView.addFooterView(footerView);
		
		mListAdapter = new LeaderboardAdapter(mContext, shost, subjectList);
		mListView.setAdapter(mListAdapter,true);
		
		mListView.setOnItemClickListener(new ListItemOnClickListener());
		mGridView.setOnItemClickListener(new GridItemOnClickListener());
		
		
		waittingProgress = (ColorBallProgressView) findViewById(R.id.leaderboard_progress); 
		waittingll = (LinearLayout) findViewById(R.id.leaderboard_waitting_ll);
		waittingll.setOnClickListener(this);
	}
	
	private void iniData(){
		//TODO 
//		showWaitting(true);
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.default_720_340)
		.showImageForEmptyUri(R.drawable.default_720_340)
		.showImageOnFail(R.drawable.default_720_340)
		.cacheInMemory(true)
		.cacheOnDisk(true)
		.considerExifParams(true)
		.build();
		
		//TODO 测试数据
//		url="[host]/player/specllist?tmpid=15&ifp=0&clid=52503";
			
		// 如果没有网络，则不向服务器申请数据
		if (FoneUtil.isNetOkWithToast(this) && !TextUtils.isEmpty(url) && url.length() > 14) {
				showWaitting(true);
				Request.getInstance().specllist(FoneUtil.onlineUrl(url), new LeaderboardCallBack());
				L.v(TAG, "iniData", FoneUtil.onlineUrl(url));
		}
	}

	/**
	 * 填充数据
	 * @param t
	 */
	private void fillData(SpecllistRst t){
		
		
		if(t.result != 0){//数据错误
			mListView.stopRefresh();
			mListView.stopLoadMore();
			showWaitting(false);
			return;
		}
		title = t.desc;
		mTitleTv.setText(t.desc);
		mTitleTv.setVisibility(View.VISIBLE);
		
		//填充数据
		headerView.setVisibility(View.VISIBLE);
		getServerData(t);
		if(!TextUtils.isEmpty(t.memo)){
			memo.setText("\u3000\u3000\u3000\u3000"+t.memo.replace("\t", "").trim());
		}
		if(t.pic!=null){
			System.out.println(FoneUtil.getAbsoluteUrl("", shost, t.pic)+"****");
			ImageLoader.getInstance().displayImage(FoneUtil.getAbsoluteUrl("", shost, t.pic), posterPic, options);
		}
		
		frashColumnListView(t);
		
		mListAdapter.initData(shost, subjectList);
		footerView.setVisibility(View.VISIBLE);
		mGridAdapter.initData(shost, subjectList);
		mGridAdapter.notifyDataSetChanged();
		mListAdapter.notifyDataSetChanged();
		
		mListView.stopRefresh();
		mListView.stopLoadMore();
		showWaitting(false);
	}
	
	
	
	/**
	 * 刷新"列表"数据
	 */
	private void frashColumnListView(SpecllistRst t) {
		// TODO Auto-generated method stub
		if(t.cnts != null && t.cnts.cntList != null && !t.cnts.cntList.isEmpty()){
			
			if(subjectList.size()>0){
				subjectList.clear();
				mListAdapter.initData(shost, subjectList);
				mGridAdapter.initData(shost, subjectList);
				mGridAdapter.notifyDataSetChanged();
				mListAdapter.notifyDataSetChanged();
			}
			
			for (Cnt cnt : t.cnts.cntList) {
				SubjectInfo info = new SubjectInfo();
				info.name = cnt.name;
				info.utp = cnt.utp;
				info.url = cnt.url;
				info.dfnt = cnt.dfnt;
				info.vgurl = cnt.url;
				info.xyzplayurl = cnt.url;
				info.btnply = cnt.btnply;
				info.weibourl = cnt.weibourl;
				info.pic1 = cnt.pic1;
				info.pic2 = cnt.pic2;
				info.ourl = cnt.ourl;
				info.quality = cnt.quality;
				info.updatedetail = cnt.updatedetail;
				info.desc = cnt.desc;
				info.showcount = cnt.showcount;
				
				subjectList.add(info);
			}
		}
	}
	
	/**
	 * 封装播放bean
	 * @param info
	 * @return
	 */
	private RedirectInfo getRedirectInfo(SubjectInfo info){
		RedirectInfo redirectInfo = new RedirectInfo();
		redirectInfo.host = host;
		redirectInfo.utp = info.utp;
		redirectInfo.weibourl = info.weibourl;
		redirectInfo.url = info.url;
		redirectInfo.vgurl = info.url;
		redirectInfo.xyzplayurl = info.url;
		redirectInfo.dnfs = info.dfnt;
		redirectInfo.name = info.name;
		redirectInfo.ourl = info.ourl;
		redirectInfo.btnply = info.btnply;
		redirectInfo.pic = info.pic2;
		return redirectInfo;
	}
	
	/**
	 * 初始化服务器返回参数
	 */
	private void getServerData(SpecllistRst t) {
		// TODO Auto-generated method stub
		if(t.shost != null){
			shost = t.shost;
			L.v(TAG, "initServerInfo", "-shost-" + shost);
		}
		
		if(t.host != null){
			host = t.host;
			L.v(TAG, "initServerInfo", "-host-" + host);
		}
		
		if(t.label != null && t.label.clid != null){
			clid = t.label.clid;
			L.v(TAG, "initServerInfo", "-clid-" + clid);
		}
		
		if(t.desc != null){
			mTitleTv.setText(t.desc);
			L.v(TAG, "initServerInfo", "-desc-" + t.desc);
		}
		
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.common_title_left_bt:
			finish();
			break;
			
		default:
			break;
		}
	}
	
	/**
	 * ListItem OnClickListener
	 * @author kliu
	 */
	private class ListItemOnClickListener implements OnItemClickListener{

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
				L.v(TAG, "ListItemOnClickListener", "position : " + position);
				
				int temp = position-2;
				
				if(temp>=0&&temp<4&&temp<=subjectList.size()){
					L.v(TAG, "ListItemOnClickListener", subjectList.get(temp).name);
					Activity2poster.startActivity(LeaderboardActivity.this, getRedirectInfo(subjectList.get(temp)));
				}
		}
	}
	
	/**
	 * GridItem OnClickListener
	 * @author kliu
	 */
	private class GridItemOnClickListener implements OnItemClickListener{
		
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			L.v(TAG, "GridItemOnClickListener", "position : " + position);
			
			int temp = position+4;
			
			if(temp<=subjectList.size()&&temp>3){
				L.v(TAG, "ListItemOnClickListener", subjectList.get(temp).name);
				Activity2poster.startActivity(LeaderboardActivity.this, getRedirectInfo(subjectList.get(temp)));
			}
		}
	}
	
	private class LeaderboardCallBack implements Callback<SpecllistRst> {

		@Override
		public void onSuccess(SpecllistRst t) {
			L.v(TAG, "SubjectCallBack", "-onSuccess-  result : " + t.result);
			fillData(t);
		}

		@Override
		public void onFailure(Error error) {
			L.v(TAG, "SubjectCallBack", "-onFailure-" + error.toString());
			mListView.stopRefresh();
			mListView.stopLoadMore();
			showWaitting(false);
			if(error.isNetworkError()){
				FoneUtil.showToast(mContext, "网络超时，请稍后重试");
			}else{
				FoneUtil.showToast(mContext, "数据获取失败，请稍后重试");
			}
		}

	}
	
	/**
	 * waitting 显示与否
	 * @param show
	 */
	private void showWaitting(boolean show){
		if(show){
			waittingll.setVisibility(View.VISIBLE);
			waittingProgress.setVisibility(View.VISIBLE);
		}else{
			waittingProgress.setVisibility(View.GONE);
			waittingll.setVisibility(View.GONE);
		}
	}

	@Override
	public void onRefresh() {
		mListView.onLoad();
		
		//TODO 测试数据
//		url="[host]/player/specllist?tmpid=15&ifp=0&clid=52503";
		
		if (FoneUtil.isNetOkWithToast(this) && !TextUtils.isEmpty(url) && url.length() > 14) {
				waittingll.setVisibility(View.VISIBLE);
				Request.getInstance().specllist(FoneUtil.onlineUrl(url), new LeaderboardCallBack());
				L.v(TAG, "onRefresh", FoneUtil.onlineUrl(url));
		}
	}

	@Override
	public void onLoadMore() {}
	
}
